<template>
  <div>
    <!-- 页面头部 黑马优购-->
    <van-nav-bar title="黑马优购" left-text="返回" left-arrow @click-left="onClickLeft" fixed />
    <div class="box">
    <!-- 地址列表 -->
    <van-address-list
      v-model="judgesID"
      :list="list"
      default-tag-text="默认"
      @add="onAdd"
      @edit="onEdit"
      @select="onSelect"
    />
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";

export default {
  data() {
    return {
      title: "黑马优购",
      rightText: "",
      url: "黑马优购",
      // 选中那个框Id
      judgesID: 1,
      list: []
    };
  },
  components: {},
  created() {
    this.$store.commit("setIfShow", false);  
    this.getlist();
  },
  methods: {
    //
    ...mapMutations(["addSelect", "addModify", "addlistk", "judge", "trigger"]),
    onClickLeft() {
      if (sessionStorage.getItem("details")) {
        this.$router.push("details");
        sessionStorage.removeItem("details");
      } else {
        this.$router.push("/orders");
      }
    },

    onClickRight() {},
    // 生命周期
    getlist() {
      const data = localStorage.getItem("list");
      if (!data) {
        return;
      } else {
        this.list = JSON.parse(data);
        this.list.forEach(item => {
          item.address = item.address.slice(0, 4);
        });

        this.addlistk();
        this.judgesID = this.judges;
      }
    },
    // 添加地址
    onAdd(val) {
      this.judge();
      this.$router.push("/addressedit");
    },
    // 修改触发
    onEdit(val) {
      const data = localStorage.getItem("list");
      this.list = JSON.parse(data);
      const index = this.list.findIndex(item => {
        return item.id === val.id;
      });
      this.addModify(this.list[index]);
      this.$router.push("/addressedit");
    },
    // 	切换选中的地址时触发
    onSelect(val) {
      this.trigger(val);
      this.getlist();
      this.judgesID = this.judges;
      //   传值选中的id
      this.addSelect(val.id);
    }
  },
  computed: {
    //   获取数据和id值
    ...mapState(["judges"])
  }
};
</script>
<style lang="less" scoped>
.van-address-list {
  margin-top: 45px;
}
.box {
  margin-top: 45px;
}
</style>